// 百度AI图像识别服务
const API_CONFIG = require('../config/api.js');

class BaiduAIService {
  constructor() {
    this.accessToken = null;
    this.tokenExpireTime = 0;
  }

  /**
   * 封装 wx.request 为 Promise
   */
  request(options) {
    return new Promise((resolve, reject) => {
      wx.request({
        ...options,
        success: (res) => {
          if (res.statusCode >= 200 && res.statusCode < 300) {
            resolve(res);
          } else {
            reject(new Error(`HTTP ${res.statusCode}: ${typeof res.data === 'object' ? JSON.stringify(res.data) : res.data}`));
          }
        },
        fail: (err) => {
          reject(new Error(err && err.errMsg ? err.errMsg : 'Network request failed'));
        }
      });
    });
  }

  /**
   * 获取Access Token
   */
  async getAccessToken() {
    // 如果token还有效，直接返回
    if (this.accessToken && Date.now() < this.tokenExpireTime) {
      return this.accessToken;
    }

    try {
      // x-www-form-urlencoded 需使用查询串格式
      const formBody = `grant_type=client_credentials&client_id=${encodeURIComponent(API_CONFIG.BAIDU_AI.API_KEY)}&client_secret=${encodeURIComponent(API_CONFIG.BAIDU_AI.SECRET_KEY)}`;
      const response = await this.request({
        url: API_CONFIG.BAIDU_AI.ACCESS_TOKEN_URL,
        method: 'POST',
        data: formBody,
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      });

      if (response.data && response.data.access_token) {
        this.accessToken = response.data.access_token;
        // 设置过期时间（提前5分钟过期，确保安全）
        this.tokenExpireTime = Date.now() + (response.data.expires_in - 300) * 1000;
        console.log('获取Access Token成功');
        return this.accessToken;
      } else {
        throw new Error('获取Access Token失败: ' + JSON.stringify(response.data));
      }
    } catch (error) {
      console.error('获取Access Token失败:', error);
      throw new Error('获取Access Token失败: ' + (error && error.message ? error.message : '未知错误'));
    }
  }

  /**
   * 将图片转换为base64格式
   */
  async imageToBase64(imagePath) {
    return new Promise((resolve, reject) => {
      wx.getFileSystemManager().readFile({
        filePath: imagePath,
        encoding: 'base64',
        success: (res) => {
          resolve(res.data);
        },
        fail: (error) => {
          console.error('图片转base64失败:', error);
          reject(new Error('图片处理失败'));
        }
      });
    });
  }

  /**
   * 识别食物图片
   */
  async recognizeFood(imagePath) {
    try {
      // 获取access token
      const accessToken = await this.getAccessToken();
      
      // 将图片转换为base64
      const base64Image = await this.imageToBase64(imagePath);
      
      // 调用百度AI图像识别接口
      const formBody = `image=${encodeURIComponent(base64Image)}&top_num=5&filter_threshold=0.7`;
      const response = await this.request({
        url: `${API_CONFIG.BAIDU_AI.IMAGE_RECOGNITION_URL}?access_token=${encodeURIComponent(accessToken)}`,
        method: 'POST',
        data: formBody,
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      });

      if (response.data && response.data.result) {
        console.log('食物识别成功:', response.data.result);
        return this.parseRecognitionResult(response.data.result);
      } else {
        throw new Error('识别失败: ' + JSON.stringify(response.data));
      }
    } catch (error) {
      console.error('食物识别失败:', error);
      throw error;
    }
  }

  /**
   * 解析识别结果
   */
  parseRecognitionResult(results) {
    if (!results || results.length === 0) {
      throw new Error('未识别到任何食物');
    }

    const foodList = results.map((item, index) => {
      // 根据食物名称获取对应的图标和营养信息
      const foodInfo = this.getFoodInfo(item.name);
      
      return {
        name: item.name,
        confidence: Math.round(item.probability * 100), // 转换为百分比
        weight: foodInfo.defaultWeight,
        minWeight: foodInfo.minWeight,
        maxWeight: foodInfo.maxWeight,
        icon: foodInfo.icon,
        iconClass: foodInfo.iconClass,
        calories: foodInfo.caloriesPer100g,
        nutrition: foodInfo.nutrition
      };
    });

    return {
      success: true,
      foodList: foodList,
      totalCalories: this.calculateTotalCalories(foodList),
      nutritionData: this.calculateNutritionData(foodList)
    };
  }

  /**
   * 获取食物信息（包含图标、营养数据等）
   */
  getFoodInfo(foodName) {
    // 食物信息数据库（实际项目中应该从服务器获取）
    const foodDatabase = {
      '米饭': {
        icon: '🍚',
        iconClass: 'rice-icon',
        defaultWeight: 200,
        minWeight: 50,
        maxWeight: 300,
        caloriesPer100g: 130,
        nutrition: { protein: 2.6, fat: 0.3, carb: 28.6 }
      },
      '红烧肉': {
        icon: '🥩',
        iconClass: 'meat-icon',
        defaultWeight: 150,
        minWeight: 50,
        maxWeight: 250,
        caloriesPer100g: 300,
        nutrition: { protein: 15, fat: 25, carb: 5 }
      },
      '青菜': {
        icon: '🥬',
        iconClass: 'vegetable-icon',
        defaultWeight: 100,
        minWeight: 50,
        maxWeight: 200,
        caloriesPer100g: 20,
        nutrition: { protein: 2, fat: 0.2, carb: 4 }
      },
      '面条': {
        icon: '🍜',
        iconClass: 'noodle-icon',
        defaultWeight: 200,
        minWeight: 100,
        maxWeight: 300,
        caloriesPer100g: 110,
        nutrition: { protein: 4, fat: 1, carb: 22 }
      },
      '鸡蛋': {
        icon: '🥚',
        iconClass: 'egg-icon',
        defaultWeight: 60,
        minWeight: 30,
        maxWeight: 100,
        caloriesPer100g: 155,
        nutrition: { protein: 13, fat: 11, carb: 1 }
      },
      '苹果': {
        icon: '🍎',
        iconClass: 'fruit-icon',
        defaultWeight: 150,
        minWeight: 100,
        maxWeight: 250,
        caloriesPer100g: 52,
        nutrition: { protein: 0.3, fat: 0.2, carb: 14 }
      }
    };

    // 尝试精确匹配
    if (foodDatabase[foodName]) {
      return foodDatabase[foodName];
    }

    // 模糊匹配
    for (const [key, value] of Object.entries(foodDatabase)) {
      if (foodName.includes(key) || key.includes(foodName)) {
        return value;
      }
    }

    // 默认返回通用食物信息
    return {
      icon: '🍽️',
      iconClass: 'default-food-icon',
      defaultWeight: 150,
      minWeight: 50,
      maxWeight: 250,
      caloriesPer100g: 100,
      nutrition: { protein: 5, fat: 5, carb: 15 }
    };
  }

  /**
   * 计算总热量
   */
  calculateTotalCalories(foodList) {
    return foodList.reduce((total, food) => {
      return total + (food.calories * food.weight / 100);
    }, 0);
  }

  /**
   * 计算营养数据
   */
  calculateNutritionData(foodList) {
    let totalProtein = 0;
    let totalFat = 0;
    let totalCarb = 0;
    let totalWeight = 0;

    foodList.forEach(food => {
      const weight = food.weight;
      totalWeight += weight;
      totalProtein += food.nutrition.protein * weight / 100;
      totalFat += food.nutrition.fat * weight / 100;
      totalCarb += food.nutrition.carb * weight / 100;
    });

    if (totalWeight === 0) {
      return { protein: 33, fat: 33, carb: 34 };
    }

    const totalNutrients = totalProtein + totalFat + totalCarb;
    if (totalNutrients === 0) {
      return { protein: 33, fat: 33, carb: 34 };
    }

    return {
      protein: Math.round((totalProtein / totalNutrients) * 100),
      fat: Math.round((totalFat / totalNutrients) * 100),
      carb: Math.round((totalCarb / totalNutrients) * 100)
    };
  }
}

// 创建单例实例
const baiduAIService = new BaiduAIService();

module.exports = baiduAIService;
